<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-15 15:28:35
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="diurnalCurve">
        <!-- <nu-col :span="24" style="height:calc(130px - 20px);"> -->
        <!-- <nutbTitle title="全日曲线"></nutbTitle> -->
        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="日期" prop="dataTime" width="520px">
                <el-date-picker v-model="formData.dataTime" type="datetimerange" placeholder="请选择日期" style="width: 100%;"
                    value-format="yyyy-MM-dd HH:mm:ss" :clearable="false" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchLine">搜索</nu-button>
                <!-- <nu-button class="searchButton" @click="clearParams">清除</nu-button> -->
                <!-- <nu-button type="primary" class="searchButton" @click="callBtn">召唤</nu-button> -->
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <!-- </nu-col> -->
        <!-- <nu-col :span="24" style="width:100%;height: calc(100% - 130px - 20px);"> -->
        <nu-row class="row" :gutter="20">
            <nu-col :span="6" class="col" style="height: 100%;">
                <nuTree v-model="currentLivingObj.id" :options="treeData" :props="defaultProps"
                    @onClickNode="handleNodeClick"></nuTree>
            </nu-col>
            <nu-col :span="18" class="col" style="height: 100%;overflow: hidden;">
                <div style="height:calc(100vh - 220px - 120px)">
                    <nu-echarts width="auto" height="100%" :option="lineOption" class="echarts"
                        v-if="isEchart"></nu-echarts>
                </div>
                <div style="height:30%">
                    <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options">
                    </NuTableList>
                </div>
            </nu-col>
        </nu-row>
        <!-- </nu-col> -->
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import nuEcharts from "@/components/base/echarts"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuRow from "@/components/base/row.vue";
import nuTree from "@/components/base/tree";
import * as echarts from 'echarts';
import { getDateTime } from "@/utils/ruoyi";
export default {
    name: "diurnalCurve",
    components: { nuCol, nutbTitle, nuEcharts, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuRow, nuTree },
    data() {
        return {
            formData: { dataTime: [] },
            fyButtons: [],
            isEchart: true,
            lineOption: {
                color: ['#40b0e2', '#69e5c1', '#626b90', '#a0a7e5'],
                title: {
                    text: '',
                    left: '0',
                    textStyle: {
                        fontWeight: "normal"
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: [],
                },
                yAxis: {
                    type: 'value',
                    name: '',
                    scale: true
                },
                grid: {
                    left: '5%',
                    right: '3%',
                },
                series: [
                    {
                        data: [],
                        type: 'line',
                        showAllSymbol: true,
                        symbolSize: 0,
                        smooth: false,
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: 'rgba(64, 176, 226,0.8)',
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(64, 176, 226,0.1)',
                                },
                            ]),
                        },
                    },
                ],
            },
            dataSource: [],
            columns: [],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                isNoSetHeight: true,
                height: '100px'
            },
            treeTitle: '',
            treeData: [],
            defaultProps: {
                parent: 'parentId',   // 父级唯一标识
                value: 'id',          // 唯一标识
                label: 'name',       // 标签显示
                children: 'children', // 子级
                renderContent: this.renderContent,
                defaultExpandAll: false,
                defaultExpandedKeys: []
            },
            currentLivingObj: { id: '' }
        };
    },
    created() {
    },
    mounted() {
        this.formData.dataTime = [getDateTime('day') + ' 00:00:00', getDateTime('day') + ' 23:59:59']
        this.getTreeData()
    },
    methods: {
        /**
         * 查询
         */
        searchLine() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getDiurnalCurve();
            }
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 召唤
         */
        callBtn() { },
        /**
         * tree节点单击
         */
        handleNodeClick(item, data) {
            this.currentLivingObj = item
            this.currentLivingObj['level'] = data.level
            this.lineOption.title.text = item.name + '变化趋势'
            this.getDiurnalCurve()
        },
        /**
         * 获取曲线数据
         */
        getDiurnalCurve() {
            if (!this.currentLivingObj?.id || this.currentLivingObj.level == 1 || this.currentLivingObj.level == 2 || this.currentLivingObj.level == 3) {
                this.$message({
                    type: 'info',
                    message: '请先选择设备'
                });
                return false
            }
            // let text = this.currentLivingObj.level == 2 ? '母线电压曲线' : '实发功率曲线'
            let postData = {
                meterId: this.currentLivingObj.modelId,
                startDay:this.formData.dataTime[0],
                endDay:this.formData.dataTime[1],
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.columns = [{
                label: '',
                prop: 'name',
                width: '220px',
                show: true,
                render: () => { }
            }]
            let obj = {}, xAxis = [], series = [];
            this.$httpGet(window.api.getDiurnalLineData, postData).then(res => {
                if (res.code == 200) {
                    this.isEchart = false
                    this.lineOption.xAxis.data = res.energyCharts[0].xaxis
                    this.lineOption.series[0].data = res.energyCharts[0].energys
                    this.columns[0].render = (h, params) => {
                        let unit = res.energyCharts[0].unit ? `（${res.energyCharts[0].unit}）` : ''
                        return h('span', params.row.name + unit);
                    }
                    this.lineOption.tooltip.formatter = (params) => {
                        let str = ''
                        params.forEach(item => {
                            let unit = res.energyCharts[0].unit ? `（${res.energyCharts[0].unit}）` : ''
                            str += `${item.name}<br/>
                            ${item.marker}${item.value}${unit}
                            `
                        })
                        return str
                    }
                    res.energyCharts[0].tableDatas.forEach((item, i) => {
                        this.columns.push({
                            label: item.time,
                            prop: item.time,
                        })
                        obj[item.time] = item.energy
                    })
                    obj['name'] = res.energyCharts[0].meterName
                    // this.lineOption.title.text = text
                    this.dataSource = [obj]
                    this.$nextTick(() => {
                        this.isEchart = true
                    })
                } else {
                    this.dataSource = []
                }
            }).catch(err => {
                this.dataSource = []
            });
        },
        //获取树形控件
        getTreeData() {
            this.defaultProps.defaultExpandedKeys = []
            this.$httpGet(window.api.getTreeData).then(res => {
                if (res.code == 200) {
                    let obj = null
                    this.treeData.push(res)
                    res.children.forEach(item => {
                        this.defaultProps.defaultExpandedKeys.push(item.id)
                        if (item?.children?.[0]?.children?.[0] && !obj) {
                            obj = item.children[0].children[0]
                            return false
                        }
                    })
                    this.currentLivingObj = obj
                    this.currentLivingObj['level'] = 4
                    this.currentLivingObj.id = obj.id
                    this.getDiurnalCurve()
                } else {
                }
            }).catch(err => { });
        },
        renderContent(h, { node, data, store }) {
            if (node.level == 3 && data.online == 1) {
                return (
                    <span class="custom-tree-node mainChannel">
                        <span>{node.label}</span>
                    </span>);
            } else {
                return (
                    <span class="custom-tree-node">
                        <span>{node.label}</span>
                    </span>);
            }
        }
    }
};
</script>
    
<style scoped lang="scss">
.diurnalCurve {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    // align-items: center;
    position: relative;
    flex-wrap: wrap;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 15px;
    right: 10px;
}

.row {
    height: calc(100% - 90px);
    width: 100%;
}

// .col {
//     height: 100%;
// }
::v-deep .mainChannel {
    color: rgba(72, 118, 255, 1);
}
</style>
    
    